//
//  UNUserNotificationCenter+Ext.swift
//  TTCOM-iOS
//
//  Created by Toj on 11/2/22.
//

import UIKit

/** 本地通知
 *  通知触发模式有下面四种:
 *  UNPushNotificationTrigger: 系统自动设置（是区分本地通知和远程通知的标识）
 *  UNTimeIntervalNotificationTrigger: 我们设置的指定什么时间后触发
 *  UNCalendarNotificationTrigger: 指定一个日期然后去触发
 *  UNLocationNotificationTrigger: 根据位置来触发，进入某地或者离开某地或者都可以触发
 */
public extension UNUserNotificationCenter {
    /**
     * 添加预约本地通知
     * id: 本地推送通知的唯一标识
     * title: 标题, 一行显示
     * subtitle: 子标题, 一行显示
     * body: 内容, 多行显示, 最多4行
     * userInfo: 附带信息
     * timeInterval: 触发时间
     * repeats: 是否循环触发, 隔timeInterval循环触发
     * completion: 添加后回调
     *
     * note:
     * title, subtitle, body必须有一个要有值否则会弹出横幅
     * badge: NSNumber, App右上角显示推送数量, 未使用
     * launchImageName: String, 未使用
     * threadIdentifier: String, 未使用
     * categoryIdentifier: String, 标识符, 未使用
     * attachments: [UNNotificationAttachment], 附件 可以是音频、图片、视频, 未使用
     */
    func nf_addSubscribe(id: String, title: String = "", subtitle: String = "", body: String = "", userInfo: [AnyHashable : Any], timeInterval: TimeInterval, repeats: Bool = false, completion:((_ error: Error?) -> Void)? = nil) {
        let content = UNMutableNotificationContent()
        content.sound = .default
        content.title = title
        content.subtitle = subtitle
        content.body = body
        content.userInfo = userInfo
        /*
        // 标识符
        content.categoryIdentifier = id
        
        if let url = Bundle.main.url(forResource: "ic_succeed_green@2x", withExtension: "png"),
           let attachment = try? UNNotificationAttachment(identifier: "imageIndetifier", url: url, options: nil) {
            content.attachments = [attachment]
        }
        */
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: repeats)
        let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
        add(request, withCompletionHandler: completion)
        
#if DEBUG
        var contentString = ""
        [title, subtitle, body].forEach { string in
            if !contentString.isEmpty {
                contentString += "\n"
            }
            if string.isEmpty { return }
            contentString += string
        }
        
        print("-->toj: addSubscribe: contentString: \(contentString), userInfo:\(userInfo), time:\(timeInterval)")
#endif
    }
    
    func removeSubscribe(id: String) {
        removePendingNotificationRequests(withIdentifiers: [id])
    }
    
    func removeAllSubscribe() {
        removeAllPendingNotificationRequests()
    }
}

